package com.pega.eprescription.customview;

import java.util.ArrayList;
import java.util.List;

import com.pega.eprescription.R;
import com.pega.eprescription.config.Defines;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;



public class MySeekBar extends RelativeLayout
{
	SeekBar eSurveySeekBar;
    int m_lastSeek;
    int m_curSeek;
    int mLastTitleIndex = 0;
    int MIN_STOP_SEEK = 1;
    private List<Integer> m_stopSeek;
    boolean isViewThumbTitle;
    public OnTouchListener onTouchListener;

    TextView thumbView;

    List<TextView> m_titleList;

    public MySeekBar( Context context)
    {
        super(context);
        init(context);
    }

    public MySeekBar( Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context);
    }

    public MySeekBar( Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(context);
    }

    public void setStopSeek( List<Integer> stopSeek)
    {
        if (stopSeek.size() > MIN_STOP_SEEK)
        {
            m_stopSeek = stopSeek;
            if (isViewThumbTitle == true)
                updateThumbLable();
        }

    }

    public List<Integer> getListStopSeek()
    {
        return this.m_stopSeek;
    }

    public void setMinTitle(String title)
    {
    	TextView v = (TextView)findViewById(R.id.esurveySeekbarMinTitle);
    	v.setText(title);
    }
    
    public void setMaxTitle(String title)
    {
    	TextView v = (TextView)findViewById(R.id.esurveySeekbarMaxTitle);
    	v.setText(title);
    }

    private void updateThumbLable()
    {
        if (!isViewThumbTitle)
            return;
        String str = "";
        try
        {
            int stepWidth = this.getMax() / (m_stopSeek.size() - 1);
            mLastTitleIndex = Math.round((float)eSurveySeekBar.getProgress() / stepWidth);
            str = m_stopSeek.get(mLastTitleIndex) + "";
        } catch (Exception e)
        {

        }

        thumbView.setText(str);

        if (eSurveySeekBar.getWidth() == 0)
        	return;
        
        int available = eSurveySeekBar.getWidth() - eSurveySeekBar.getPaddingLeft() - eSurveySeekBar.getPaddingRight();
        float scale = (float) eSurveySeekBar.getProgress() / (float)eSurveySeekBar.getMax();
        available -= eSurveySeekBar.getThumb().getIntrinsicWidth();

        // The extra space for the thumb to move on the track
        available += eSurveySeekBar.getThumbOffset() * 2;

        int lefMargin = (int) (scale * available) + eSurveySeekBar.getLeft() - thumbView.getWidth() / 2 + 20;
        LayoutParams params = (RelativeLayout.LayoutParams)thumbView.getLayoutParams();
        params.setMargins((int)lefMargin, params.topMargin, params.rightMargin, params.bottomMargin);
        
       
    }

    public int getValueOfIndex(int index)
    {
        try
        {
            if (m_stopSeek.size() > MIN_STOP_SEEK)
            {
                return m_stopSeek.get(index);
            }
        } catch (Exception e)
        {
            return 0;
        }
        return 0;
    }

    

    public int getValueIndex()
    {
        int stepWidth = this.getMax() / (m_stopSeek.size() - 1);
        return Math.round((float)eSurveySeekBar.getProgress() / stepWidth);
    }

    public int getCurrentValue()
    {
        return m_stopSeek.get(mLastTitleIndex);
    }
    public int getIndexOfValue(int value)
    {
        int index = 0;
        int distance = getMax();
        if (m_stopSeek.size() > 1)
        {
            for (int i = 0; i < m_stopSeek.size(); i++)
            {
                if (Math.abs(m_stopSeek.get(i) - value) < distance)
                {
                    distance = Math.abs(m_stopSeek.get(i) - value);
                    index = i;
                }
            }

        }
        return index;
    }

    public void setIsThumbTitle(boolean is)
    {
        isViewThumbTitle = is;
        
        if (isViewThumbTitle == false)
        {
            thumbView.setVisibility(INVISIBLE);
        } else
        {
            thumbView.setVisibility(VISIBLE);
        }
    }

    public void SetProgressByUser(int progress)
    {
        if (m_stopSeek != null && m_stopSeek.size() > MIN_STOP_SEEK)
        {
        	eSurveySeekBar.setProgress(m_stopSeek.get(getIndexOfValue(progress)));
        } else
        {
        	eSurveySeekBar.setProgress(progress);
        }
    }

    @SuppressLint("NewApi")
    void runAnim()
    {
        ValueAnimator anim = ValueAnimator.ofInt(m_lastSeek, m_curSeek);
        float duration = Defines.ANIMATION_MAX_DURATION / eSurveySeekBar.getMax()
                * Math.abs(m_lastSeek - m_curSeek);
        if (duration < Defines.ANIMATION_MIN_DURATION)
        {
            duration = Defines.ANIMATION_MIN_DURATION;
        }
        anim.setDuration((long) duration);
        anim.addUpdateListener(new AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate( ValueAnimator animation)
            {
                int animProgress = (Integer) animation.getAnimatedValue();
                try
                {
                	eSurveySeekBar.setProgress(animProgress);
                } catch (Exception e)
                {
                    //seekBar.setProgress(m_curSeek);
                }

            }
        });

        anim.start();
    }

 
    
    public int getMax()
    {
    	return eSurveySeekBar.getMax();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        return true;
    }
    
    protected void setLayout( Context context) 
    {
		
		LayoutInflater inflater = (LayoutInflater) context
		        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		    inflater.inflate(R.layout.esurvey_seekbar, this, true);
		eSurveySeekBar = (SeekBar)findViewById(R.id.esurveySeekBar);
		thumbView = (TextView)findViewById(R.id.esurveySeekbarThumbLabel);
	}
    void init( Context context)
    {
    	setLayout(context);
    	
    	eSurveySeekBar.setMax(1000);

        m_stopSeek = new ArrayList<Integer>();
        m_titleList = new ArrayList<TextView>();

        setEnabled(true);

        setOnFocusChangeListener(new OnFocusChangeListener()
		{
			
			@Override
			public void onFocusChange(View v, boolean hasFocus)
			{
				if (hasFocus && isViewThumbTitle == true)
				{
		           updateThumbLable();
				}
			}
		});
        onTouchListener = new OnTouchListener()
        {

            @SuppressLint("NewApi")
            @Override
            public boolean onTouch( View v,  MotionEvent event)
            {
                int[] position = new int[2];
                v.getLocationInWindow(position);
                if (event.getAction() == MotionEvent.ACTION_DOWN)
                {

                    m_lastSeek = eSurveySeekBar.getProgress();
                    m_curSeek = (int) ((event.getRawX() - position[0])
                            * eSurveySeekBar.getMax() / eSurveySeekBar.getWidth());

                    int posCur = eSurveySeekBar.getMax();
                    for (Integer i : m_stopSeek)
                    {
                        if ((Math.abs(i - m_curSeek)) < (Math.abs(posCur
                                - m_curSeek)))
                        {
                            posCur = i;
                        }
                    }
                    m_curSeek = posCur;

                    return true;
                }
                if (event.getAction() == MotionEvent.ACTION_MOVE)
                {
                    // isDoneTouch = false;
                    m_curSeek = (int) ((event.getRawX() - position[0])
                            * eSurveySeekBar.getMax() / eSurveySeekBar.getWidth());

                    eSurveySeekBar.setProgress(m_curSeek);
                    m_lastSeek = m_curSeek;
                    return true;
                }
                if (event.getAction() == MotionEvent.ACTION_UP)
                {
                    m_curSeek = (int) ((event.getRawX() - position[0])
                            * (float)eSurveySeekBar.getMax() / eSurveySeekBar.getWidth());

                    int stepWidth = eSurveySeekBar.getMax() / (m_stopSeek.size() - 1);
                    m_lastSeek = Math.round((float)m_curSeek / stepWidth) * stepWidth;

                    eSurveySeekBar.setProgress(m_lastSeek);
                    updateThumbLable();
                    return true;
                }
                return false;
            }
        };
        eSurveySeekBar.setOnTouchListener(onTouchListener);
        eSurveySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
        {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar)
            {
            }

            @Override
            public void onStartTrackingTouch( SeekBar seekBar)
            {

                m_lastSeek = seekBar.getProgress();
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser)
            {
                if (isViewThumbTitle)
                {
                    updateThumbLable();
                }
            }
        });

    }

}
